package com.webull.information.center.carwler.common.util.news.detection;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.webull.information.center.carwler.common.model.NewsDetection;
import com.webull.information.center.carwler.common.util.HttpClientUtil;
import com.webull.information.center.carwler.common.util.jsoup.HttpJsoupClient;

@Component
public class DetectionGoogleList implements DetectionList {
    private final Logger logger = LogManager.getLogger(getClass());
    private @Autowired
    HttpClientUtil httpClientUtil;

    private static final String R_URL = "https://www.google.com/finance/company_news?q={0}&output=rss";

    // String url2 =
    // "https://www.google.com/finance/company_news?q=SHE:000001&ei=p5uqWNjKI4HRjAH27rbYBA&output=rss";
    @Override
    public List<NewsDetection.DetectionResult> parseNewsList(NewsDetection.Detection ticker) {
        String url = StringUtils.replaceOnce(R_URL, "{0}", ticker.getsExchange() + ":" + ticker.getsSymbol());

        SyndFeed syndFeed = httpClientUtil.retriveRssSyndFeed(url, true);
        if (syndFeed == null) {
            logger.warn("DetectionGoogleList parseNewsList parse url:{} ,doc is null!!", url);
            return null;
        }

        List<NewsDetection.DetectionResult> result = new ArrayList<>();
        List entries = syndFeed.getEntries();
        entrie:
        for (int i = 0; entries != null && i < entries.size(); i++) {
            try {
                SyndEntry entry = (SyndEntry) entries.get(i);

                NewsDetection.DetectionResult item = new NewsDetection.DetectionResult(ticker);

                item.setTitle(entry.getTitle());
                item.setUrl(entry.getLink());
                if (!StringUtils.isBlank(item.getUrl()))
                    item.setUrlMd5(HttpJsoupClient.finishingMd5Url(item.getUrl() + item.getsSource()));
                item.setNewsTime(entry.getPublishedDate());
                result.add(item);
            } catch (Exception e) {
                logger.warn(e);
                break entrie;
            }
        }

        return result;
    }

}
